<template>
  <!-- 新增餐厅/重新提交 -->
  <view class="addRestaurant">
    <view class="bgColor"></view>

    <view class="wrapper">
      <view
        class="wrapper-item"
        style="padding: 0rpx 40rpx; background-color: transparent"
      >
        <view class="steps">
          <view class="item" :class="steps == 1 ? 'active' : ''">
            <template>
              <view class="circle" v-if="steps == 2 || steps == 3">
                <u-icon name="checkbox-mark" color="#00C9AE"></u-icon>
              </view>
              <view v-else class="circle">1</view>
            </template>
            <view class="title">基本信息</view>
            <template>
              <view class="rtline lineColor" v-if="steps == 2"></view>
              <view v-else class="rtline"></view>
            </template>
          </view>
          <view class="item" :class="steps == 2 ? 'active' : ''">
            <template>
              <view class="circle" v-if="steps == 1 || steps == 2">2 </view>
              <view class="circle" v-if="steps == 3">
                <u-icon name="checkbox-mark" color="#00C9AE"></u-icon>
              </view>
            </template>
            <view class="title">营业信息</view>
            <template>
              <view class="rtline lineColor" v-if="steps == 3"></view>
              <view v-else class="rtline"></view>
            </template>
          </view>
          <view class="item" :class="steps == 3 ? 'active' : ''">
            <template>
              <view class="circle" v-if="steps == 1 || steps == 2"> 3 </view>
              <view v-else class="circle">3</view>
            </template>
            <view class="title">餐厅负责人</view>
          </view>
        </view>
      </view>

      <view class="wrapper-item content">
        <u-form
          :model="form"
          ref="form"
          label-width="280"
          labelPosition="’top‘"
          :error-type="errorType"
        >
          <template v-if="steps == 1">
            <u-form-item label="餐厅名称" borderBottom :required="true">
              <u--input
                v-model.trim="form.restaurantName"
                border="none"
                placeholder="请填写餐厅招牌名称"
                :maxlength="30"
              ></u--input>
            </u-form-item>

            <u-form-item label="门头照片" borderBottom :required="true">
              <u-upload
                :fileList="fileList2"
                @afterRead="afterDoor"
                @delete="deletePic(2)"
                name="file"
                :maxCount="1"
                width="110"
                height="90"
              >
                <image
                  :src="baseImgUrl + 'upload-icon2.png'"
                  style="width: 220rpx; height: 180rpx"
                ></image>
              </u-upload>
            </u-form-item>

            <u-form-item
              label="营业地址"
              borderBottom
              :required="true"
              @click="visibleCity = true"
            >
              <u--input
                v-model="form.regionIdDesc"
                disabled
                disabledColor="#ffffff"
                placeholder="选择区域"
                border="none"
              ></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
            <u-form-item borderBottom>
              <u--input
                v-model="form.detailAddress"
                border="none"
                placeholder="详细地址"
                :maxlength="30"
              ></u--input>
            </u-form-item>

            <u-form-item label="经纬度" borderBottom :required="true">
              <view class="map-form">
                <u--input
                  v-model="lnglat"
                  border="none"
                  placeholder="在地图上选择点位"
                  :maxlength="30"
                  :readonly="true"
                ></u--input>
                <view class="map-img" @click="mapHandle">
                  <image :src="baseImgUrl + 'map-icon.png'"></image>
                  点击选择
                </view>
              </view>
            </u-form-item>

            <u-form-item label="统一信用代码" borderBottom>
              <u--input
                v-model.trim="form.creditCode"
                border="none"
                placeholder="请填写"
                :maxlength="18"
              ></u--input>
            </u-form-item>
            <u-form-item label="营业执照企业名称" borderBottom :required="true">
              <u--input
                v-model.trim="form.businessName"
                border="none"
                placeholder="请填写营业执照上的企业名称"
                :maxlength="30"
              ></u--input>
            </u-form-item>
            <u-form-item label="营业执照照片" borderBottom :required="true">
              <u-upload
                :fileList="fileList"
                @afterRead="afterRead"
                @delete="deletePic(1)"
                name="file"
                :maxCount="1"
                width="110"
                height="90"
              >
                <image
                  :src="baseImgUrl + 'upload-icon2.png'"
                  style="width: 220rpx; height: 180rpx"
                ></image>
              </u-upload>
            </u-form-item>
          </template>

          <template v-if="steps == 2">
            <u-form-item label="灶头数" borderBottom :required="true">
              <u--input
                v-model.trim="form.stoveNum"
                border="none"
                placeholder="请填写"
                :maxlength="5"
                @blur="stoveBlur"
              ></u--input>
            </u-form-item>
            <u-form-item label="餐厅规模" borderBottom :required="true">
              <u--input
                v-model="scale"
                readonly
                border="none"
                placeholder="回显"
                :maxlength="30"
              ></u--input>
            </u-form-item>
            <u-form-item label="清洗周期" borderBottom :required="true">
              <u--input
                v-model="cleanCycle"
                readonly
                border="none"
                placeholder="回显"
                :maxlength="30"
              ></u--input>
            </u-form-item>
            <u-form-item
              label="餐饮企业类别"
              borderBottom
              :required="true"
              @click="cellClick('title', 'cttypeDesc')"
            >
              <u--input
                v-model="form.cttypeDesc"
                disabled
                disabledColor="#ffffff"
                placeholder="请选择"
                border="none"
              ></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
            <u-form-item label="营业面积" borderBottom>
              <u--input
                v-model.trim="form.businessArea"
                border="none"
                placeholder="请填写"
                :maxlength="5"
              ></u--input>
            </u-form-item>
            <u-form-item label="就餐座位数" borderBottom>
              <u--input
                v-model.trim="form.seatingCapacity"
                border="none"
                placeholder="请填写"
                :maxlength="5"
              ></u--input>
            </u-form-item>
            <u-form-item label="就业人数" borderBottom>
              <u--input
                v-model.trim="form.employment"
                border="none"
                placeholder="请填写"
                :maxlength="5"
              ></u--input>
            </u-form-item>
          </template>

          <template v-if="steps == 3">
            <u-form-item label="餐厅负责人" borderBottom :required="true">
              <u--input
                v-model="form.chargeName"
                border="none"
                placeholder="请填写负责人姓名"
                :maxlength="10"
              ></u--input>
            </u-form-item>

            <u-form-item label="负责人联系电话" borderBottom :required="true">
              <u--input
                v-model="form.chargePhone"
                border="none"
                placeholder="请填写手机号码"
                :maxlength="11"
                @blur="phoneHandle"
              ></u--input>
            </u-form-item>
            <!-- <u-form-item borderBottom>
              <view class="codeForm">
                <u--input
                  v-model="form.mobileCode"
                  placeholder="填写验证码"
                  :maxlength="6"
                  border="none"
                ></u--input>

                <u-code
                  :startText="'获取验证码'"
                  :endText="'获取验证码'"
                  ref="uCode"
                  @change="codeChange"
                ></u-code>
                <button class="lookbtn code-btn" @tap="getCode">
                  {{ tips }}
                </button>
              </view>
            </u-form-item> -->
          </template>
        </u-form>
      </view>
    </view>

    <view class="btns thispageBtn">
      <button
        v-if="steps == 1"
        class="submit-btn"
        type="primary"
        @click="nextSteps"
        icon="map"
        style="width: 100%"
      >
        下一步
      </button>
      <block v-if="steps == 2">
        <button class="previous-btn lt" type="primary" @click="steps = 1">
          上一步
        </button>
        <button class="submit-btn" type="primary" @click="nextSteps2">
          下一步
        </button>
      </block>
      <block v-if="steps == 3">
        <button class="previous-btn lt" type="primary" @click="steps = 2">
          上一步
        </button>
        <button class="submit-btn" type="primary" @click="submitHandle">
          提交
        </button>
      </block>
    </view>

    <u-picker
      :show="pickerShow"
      :columns="columns"
      :keyName="keyName"
      @confirm="showConfirm"
      @close="pickerClose"
      @cancel="pickerCancel"
      :closeOnClickOverlay="true"
    ></u-picker>

    <!-- 营业地址选项 -->
    <cityPicker
      v-if="addressList.length"
      :addressList="addressList"
      :visible="visibleCity"
      :mask-close-able="maskCloseAble"
      @confirm="cityConfirm"
      @cancel="visibleCity = false"
    />
  </view>
</template>

<script>
import {
  restaurantSendsms,
  regionTree,
  restaurantStovenum,
  restaurantSave,
  restaurantDetail,
} from "@/api/myself.js";
import { findEnableDictItemsbyCode } from "@/api/api.js";
import cityPicker from "@/components/piaoyi-cityPicker/pioayi-cityPicker.vue";
import {
  Toast,
  navBack,
  handleClickRouter,
  uniTrim,
  isNumber,
  isNumberTwo,
  regPhone,
  emitTime,
} from "@/utils/util.js";
import mixin from "@/utils/mixin.js";

export default {
  mixins: [mixin],
  components: {
    cityPicker,
  },
  data() {
    return {
      baseImgUrl: this.$baseImgUrl,
      baseURL: this.$baseURL,
      steps: 1,
      form: {},
      errorType: ["none"],
      fileList: [],
      fileList2: [],
      tips: "",
      lnglat: "", //经纬度
      policeAgencyNames: "", //记录派出所文字
      imgPrefix: uni.getStorageSync("imgPrefix"),
      options: {},
      scale: "",
      cleanCycle: "",

      addressList: [],
      visibleCity: false,
      maskCloseAble: true,
    };
  },
  onLoad(options) {
    regionTree().then((res) => {
      this.addressList = res.result || [];
    });

    this.options = JSON.parse(decodeURIComponent(options.data));
    if (this.options.id) {
      uni.setNavigationBarTitle({
        title: "重新提交",
      });

      restaurantDetail({ restaurantId: this.options.id }).then((res) => {
        if (res.code == 200) {
          this.form = res.result;
          let { businessPhoto, lng, lat, regionName, type } = res.result;

          this.fileList.push({
            url: this.imgPrefix + businessPhoto,
          });
          this.lnglat = `${lng}-${lat}`;
          this.form.regionIdDesc = regionName;
          this.stoveBlur();

          findEnableDictItemsbyCode("restaurant_type").then((res) => {
            res.result.forEach((v) => {
              if (v.value == type) {
                this.form.cttypeDesc = v.title;
              }
            });
          });
        }
      });
    }
  },
  methods: {
    handleClickRouter,
    stoveBlur() {
      let { stoveNum } = this.form;
      if (!stoveNum || !uniTrim(stoveNum)) {
        Toast("请输入灶头数");
        return;
      }

      if (!isNumber(stoveNum)) {
        Toast("灶头数请输入数字");
        return;
      }

      restaurantStovenum({ stoveNum: stoveNum }).then((res) => {
        let { scale, cleanCycle } = res.result;
        this.scale = scale == 1 ? "小型" : scale == 2 ? "中型" : "大型";
        this.cleanCycle = cleanCycle;
      });
    },
    phoneHandle() {
      if (this.form.chargePhone && !regPhone(this.form.chargePhone)) {
        Toast("请输入正确的手机号");
        return;
      }
    },
    mapHandle() {
      let _this = this;
      uni.chooseLocation({
        success: function (res) {
          let { longitude, latitude } = res;
          _this.form.lng = longitude;
          _this.form.lat = latitude;
          _this.lnglat = `${longitude}-${latitude}`;
        },
        fail: function (err) {
          console.log(err, "错误的");
        },
      });
    },
    codeChange(text) {
      this.tips = text;
    },
    cityConfirm(e) {
      this.form.regionId = e.codeLast;
      this.form.regionIdDesc = e.name;
      this.visibleCity = false;
    },
    getCode() {
      let { chargePhone } = this.form;
      if (!chargePhone) {
        Toast("请输入手机号码");
        return;
      }

      if (chargePhone && !regPhone(chargePhone)) {
        Toast("请输入正确的手机号");
        return;
      }

      if (this.$refs.uCode.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: "正在获取验证码",
        });
        setTimeout(() => {
          uni.hideLoading();
          // 这里此提示会被this.start()方法中的提示覆盖
          uni.$u.toast("验证码已发送");
          // 通知验证码组件内部开始倒计时
          this.$refs.uCode.start();

          let data = {
            mobile: this.form.chargePhone,
            smsType: "SAVE_MOBILE",
          };

          restaurantSendsms(data).then((res) => {
            if (res.code == 400) {
              Toast("验证码今日已达上限");
            }
          });
        }, 2000);
      }
    },
    afterRead(info) {
      let _this = this;
      uni.uploadFile({
        url: _this.baseURL + "/mini/sys/upload/upload_file",
        filePath: info.file.url,
        name: "file",
        header: {
          "content-type": "application/json", // 默认值
          "X-MINI-TOKEN": uni.getStorageSync("X-MINI-TOKEN"),
        },
        formData: {
          type: 3,
        },
        success(res) {
          let { fullPath, halfPath } = JSON.parse(res.data).result;
          _this.fileList.push({ url: fullPath });
          _this.form.businessPhoto = halfPath;
        },
      });
    },
    afterDoor(info) {
      let _this = this;
      uni.uploadFile({
        url: _this.baseURL + "/mini/sys/upload/upload_file",
        filePath: info.file.url,
        name: "file",
        header: {
          "content-type": "application/json", // 默认值
          "X-MINI-TOKEN": uni.getStorageSync("X-MINI-TOKEN"),
        },
        formData: {
          type: 16,
        },
        success(res) {
          let { fullPath, halfPath } = JSON.parse(res.data).result;
          _this.fileList2.push({ url: fullPath });
          _this.form.doorstepPhoto = halfPath;
        },
      });
    },
    deletePic(num) {
      if (num == 1) {
        this.fileList = [];
        this.form.businessPhoto = "";
      } else if (num == 2) {
        this.fileList2 = [];
        this.form.doorstepPhoto = "";
      }
    },
    /* cell 点击 */
    cellClick(name, type) {
      this.keyName = name;
      this.cellType = type;
      let code = "";
      switch (this.cellType) {
        case "cttypeDesc":
          code = "cttypeDesc";
          break;
        default:
          break;
      }

      if (code == "cttypeDesc") {
        findEnableDictItemsbyCode("restaurant_type").then((res) => {
          this.columns[0] = res.result || [];
          this.pickerShow = true;
        });
      }
    },
    /* 选择器 确定 */
    showConfirm(e) {
      let arr = e.value;
      if (arr.length) {
        let obj = arr[0];
        switch (this.cellType) {
          case "cttypeDesc":
            this.form.type = obj.value;
            this.form.cttypeDesc = obj.title;
            break;
          default:
            break;
        }
      }
      this.pickerShow = false;
    },
    /* steps=1  下一步 */
    nextSteps() {
      let {
        restaurantName,
        doorstepPhoto,
        regionIdDesc,
        detailAddress,
        creditCode,
        businessName,
        businessPhoto,
      } = this.form;

      if (!restaurantName || !uniTrim(restaurantName)) {
        Toast("请输入餐厅名称");
        return;
      }

      if (!doorstepPhoto) {
        Toast("请上传门头照片");
        return;
      }

      if (!regionIdDesc || !uniTrim(regionIdDesc)) {
        Toast("请选择区域");
        return;
      }

      if (!detailAddress || !uniTrim(detailAddress)) {
        Toast("请输入详细地址");
        return;
      }

      if (!this.lnglat) {
        Toast("请选择经纬度");
        return;
      }

      // if (!creditCode || !uniTrim(creditCode)) {
      //   Toast("请输入统一信用代码");
      //   return;
      // }

      let number = /^[0-9A-Z]{13,18}$/;
      if (creditCode && !number.test(creditCode)) {
        Toast("请输入正确的统一信用代码");
        return;
      }

      if (!businessName || !uniTrim(businessName)) {
        Toast("请输入营业执照企业名称");
        return;
      }

      let companyRegular = /^[\u4e00-\u9fa5]+$/;
      if (!companyRegular.test(businessName)) {
        Toast("请输入营业执照上的企业名称");
        return;
      }

      if (!businessPhoto) {
        Toast("请上传营业执照");
        return;
      }

      this.steps = 2;
    },
    /* steps=2 下一步 */
    nextSteps2() {
      let { stoveNum, cttypeDesc, businessArea, seatingCapacity, employment } =
        this.form;
      if (!stoveNum || !uniTrim(stoveNum)) {
        Toast("请输入灶头数");
        return;
      }

      if (!isNumber(stoveNum)) {
        Toast("灶头数请输入数字");
        return;
      }

      if (!cttypeDesc) {
        Toast("请选择餐饮企业类别");
        return;
      }

      if (businessArea && !isNumberTwo(businessArea)) {
        Toast("营业面积请输入数字,可精确到小数点后两位");
        return;
      }

      if (seatingCapacity && !isNumber(seatingCapacity)) {
        Toast("就餐座位数请输入数字");
        return;
      }

      if (employment && !isNumber(employment)) {
        Toast("就业人数请输入数字");
        return;
      }
      this.steps = 3;
    },
    submitHandle() {
      let {
        restaurantName,
        doorstepPhoto,
        regionId,
        detailAddress,
        lng,
        lat,
        chargeName,
        chargePhone,
        creditCode,
        businessName,
        businessPhoto,

        stoveNum,
        type,
        businessArea,
        seatingCapacity,
        employment,
      } = this.form;

      if (!chargeName || !uniTrim(chargeName)) {
        Toast("请输入餐厅负责人");
        return;
      }

      let chargeNameRegular = /^[a-zA-Z\u4e00-\u9fa5]+$/;
      if (!chargeNameRegular.test(chargeName)) {
        Toast("餐厅负责人不能输入数字和特殊字符");
        return;
      }

      if (!chargePhone) {
        Toast("请输入手机号码");
        return;
      }

      if (chargePhone && !regPhone(chargePhone)) {
        Toast("请输入正确的手机号");
        return;
      }

      let dataAll = {
        id: this.options.id || "",
        restaurantName,
        doorstepPhoto,
        regionId,
        detailAddress,
        lng,
        lat,
        chargeName,
        chargePhone,
        creditCode,
        businessName,
        businessPhoto,
        stoveNum,
        type,
        businessArea,
        seatingCapacity,
        employment,
      };

      restaurantSave(dataAll).then((res) => {
        if (res.code == 200) {
          Toast(this.options.id ? "重新成功" : "添加成功");
          emitTime("myRestaurant");
          navBack();
          return;
        }
        Toast(res.message);
      });
    },
  },
};
</script>

<style>
page {
  background-color: #f3f3f3 !important;
  height: 100%;
}
</style>
<style lang="scss" scoped>
.addRestaurant {
  flex: 1;
  background-color: #f3f3f3;
  .bgColor {
    width: 100%;
    height: 240rpx;
    background: #00c9ae;
  }

  .addRestaurant-title {
    position: absolute;
    top: 10rpx;
    left: 6%;
    color: #ffffff;
    font-size: 34rpx;
    font-weight: bold;
  }

  .wrapper {
    position: absolute;
    top: 30rpx;
    left: 50%;
    transform: translateX(-50%);
    margin-bottom: 50px;

    .wrapper-item {
      margin-bottom: 2vh;
      padding: 35rpx 40rpx;
      background-color: #ffffff;
      box-shadow: 0px 3px 6px 1px rgba(123, 123, 123, 0.2);
      border-radius: 10rpx;
      width: 702rpx;
    }

    .steps {
      display: flex;
      justify-content: space-between;
      margin: 0 auto;
      .item {
        flex: 1;
        position: relative;
        top: 0;
        left: 0;
        .title {
          font-size: 26rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #baf1ea;
          text-align: center;
          margin-bottom: 10rpx;
          margin-top: 10rpx;
        }

        .circle {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 80rpx;
          height: 80rpx;
          margin: 0 auto;
          font-size: 32rpx;
          border-radius: 50%;
          background: #99e9de;
          color: #00c9ae;
        }

        .ltline {
          position: absolute;
          bottom: 50rpx;
          left: 0;
          width: 44%;
          border-bottom: 13rpx dotted #a7cffb;
        }

        .rtline {
          position: absolute;
          bottom: 86rpx;
          right: -48rpx;
          width: 44%;
          border-bottom: 10rpx dotted #99e9de;
        }
      }

      .active {
        .title {
          color: #fff;
        }
        .circle {
          background: #fff;
          color: #00c9ae;
        }
      }

      .lineColor {
        border-bottom: 10rpx dotted #fff !important;
      }
    }

    .content {
      margin: 0 auto;
      height: calc(100vh - 167px);
      overflow-y: auto;
    }
  }

  .map-form {
    display: flex;
    .map-img {
      color: #00c9ae;
      font-size: 30rpx;
      font-weight: 500;
      image {
        display: inline-block;
        margin-right: 10rpx;
        vertical-align: top;
        width: 30rpx;
        height: 40rpx;
      }
    }
  }

  .code-btn {
    color: #2488f5;
    font-size: 28rpx;
  }

  .codeForm {
    display: flex;
    justify-content: space-around;
  }

  .thispageBtn {
    position: absolute;
    width: 100vw;
    bottom: 0;
  }
}
</style>
